Weird behavior when using pointers [migrated]

Posted by Kinan Al Sarmini on Programmers See other posts from Programmers or by Kinan Al Sarmini
Published on 2012-11-08T23:41:12Z Indexed on 2012/11/09 5:23 UTC
Read the original article Hit count: 252

Filed under:
|

When I run this code on MS VS C++ 2010:

#include <iostream>

int main() {
    const int a = 10;
    const int *b = &a;
    int *c = (int *)b;
    *c = 10000;
    std::cout << c << " " << &a << std::endl;
    std::cout << *c << " " << a << " " << *(&a) << std::endl;
    return 0;
}

The output is:

0037F784 0037F784
10000 10 10

The motivation for writing that code was this sentence from "The C++ Programming Language" by Stroustrup: "It is possible to explicitly remove the restrictions on a pointer to const by explicit type conversion".

I know that trying to modify a constant is conceptually wrong, but I find this result quite weird. Can anyone explain the reason behind it?

© Programmers or respective owner

Related posts about c++

Related posts about pointers